package com.fulihui.common.util;

import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;

import java.util.Map;
import java.util.Set;

/**
 * 十分钟未点击拉活消息
 * @author: LiuJie
 * @version: v 0.1 2018-07-05 16:45
 */

public class TenMinutesMsgUtil {
    private JedisUtil jedisUtil;
    /**
     * 新关注用户redis存放key 前缀
     */
    public static final String REDIS_SUBSCRIBE_USER_KEY = "SUK_";
    /**
     * 将要发送的48H消息内容存入redis 前缀
     */
    public static final String TEN_MINUTES_NEWS_KEY = "TEN_MIN_NEWS_";
    /**
     * 队列批次长度
     */
    public static final int mqLengthGenerally = 100;

    public TenMinutesMsgUtil(JedisUtil jedisUtil){
        this.jedisUtil = jedisUtil;
    }

    public void recordSubscribe(String appId, String openId) {
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(openId)) {
            return;
        }
        String subscribeTime = String.valueOf(System.currentTimeMillis());

        //关注用户，记录到redis
        Map<String, Double> members = Maps.newHashMap();
        members.put(openId, Double.valueOf(subscribeTime));
        jedisUtil.zadd(key(appId), members);
    }

    public void rmSubscribe(String appId, String openId) {
        if (StringUtils.isBlank(appId) || StringUtils.isBlank(openId)) {
            return;
        }
        String[] members = {openId};
        jedisUtil.zrem(key(appId), members);
    }

    /**
     * 获取所有十分钟拉活的 Key
     * @return
     */
    public Set<String> keys() {
        return jedisUtil.keys(key("*"));
    }


    private String key(String appId) {
        StringBuffer subscribeKey = new StringBuffer();
        subscribeKey.append(REDIS_SUBSCRIBE_USER_KEY)
                .append(appId);
        return subscribeKey.toString();
    }
}
